import os
import sys
import datetime
from config.settings import BASE_DIR, logger
from utils.ai_summary_utils import AISummaryUtils
from utils.docx_utils import DocxGenerator


def main():
    """
    生成班超要闻主程序
    """
    logger.info("开始生成班超要闻")
    today = datetime.date.today()
    today_date = today.strftime("%Y%m%d")
    
    # 原始内容文件路径
    raw_filename = os.path.join(BASE_DIR, "yuanshineirong", f"原始内容_{today_date}.txt")
    
    # 检查原始内容文件是否存在
    if not os.path.exists(raw_filename):
        logger.error(f"原始内容文件不存在: {raw_filename}")
        print(f"错误: 原始内容文件不存在: {raw_filename}")
        return
    
    # 创建AI总结工具实例
    ai_summary = AISummaryUtils()
    
    # 生成班超要闻.txt文件
    summary_filename = os.path.join(BASE_DIR, "zongjie", f"班超要闻-{today_date}.txt")
    result = ai_summary.generate_daily_report(raw_filename, summary_filename)
    
    if result:
        logger.info(f"班超要闻已生成: {summary_filename}")
        print(f"班超要闻已生成: {summary_filename}")
        
        # 生成Word文档
        try:
            template_path = os.path.join(BASE_DIR, "banchao.docx")
            output_path = os.path.join(BASE_DIR, "doc", f"班超要闻-{today_date}.docx")
            
            if os.path.exists(template_path):
                docx_generator = DocxGenerator(template_path)
                if docx_generator.generate_daily_report(result, output_path):
                    logger.info(f"Word文档已保存: {output_path}")
                    print(f"Word文档已保存: {output_path}")
                else:
                    logger.error("生成Word文档失败")
                    print("错误: 生成Word文档失败")
            else:
                logger.warning(f"模板文件不存在: {template_path}")
                print(f"警告: 模板文件不存在: {template_path}")
        except Exception as e:
            logger.error(f"生成Word文档时出错: {str(e)}")
            print(f"错误: 生成Word文档时出错: {str(e)}")
    else:
        logger.error("生成班超要闻失败")
        print("错误: 生成班超要闻失败")


if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        logger.info("用户中断程序执行")
        print("用户中断程序执行")
    except Exception as e:
        logger.error(f"程序执行出错: {str(e)}")
        print(f"错误: 程序执行出错: {str(e)}")
        import traceback
        traceback.print_exc()